package cn.hncj.lyc.controller.front;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import cn.hncj.lyc.bean.UserInfo;
import cn.hncj.lyc.common.Result;
import cn.hncj.lyc.common.StatusCode;
import cn.hncj.lyc.service.UserService;
import cn.hncj.lyc.service.impl.UserInfoRegServiceImpl;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserRegisterController {
	@Autowired
	private UserInfoRegServiceImpl userInfoRegServiceImpl;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 发送短信验证码
	 *测试
	 * @return
	 */
	@RequestMapping(value="/sendsms/{mobile}",method= RequestMethod.POST)
    public Result sendsms(@PathVariable String mobile ){
		userInfoRegServiceImpl.sendSms(mobile);
		return new Result(true, StatusCode.SMS, "验证码已发送至你的手机，请注意查收");
	}

	/**
	 * 用户注册
	 * @param code
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/register/{code}",method = RequestMethod.POST)
	public Result regist(@PathVariable String code,@RequestBody UserInfo user) throws Exception{
		//得到redis缓存中的验证码
		String checkcodeRedis =(String) redisTemplate.opsForValue().get("checkcode"+user.getUserPhone());
		if(checkcodeRedis==null){
			return new Result(false,StatusCode.ERROR,"请获取验证码");
		}
		 if(!checkcodeRedis.equals(code)){
			return new Result(false,StatusCode.ERROR,"验证码错误");
		}
		else {
			user.setUserType("2");
			userService.addUser(user);
			return new Result(true,StatusCode.OK,"注册成功");
		}
	}
		      
	/**
	 *判断账号是否存在
	 * @param user
	 * @return
	 */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
	@ResponseBody
    public Result findsame(@RequestBody UserInfo user){

    	System.out.println("拿到的手机号码"+user.getUserPhone());
		String phone = user.getUserPhone();

		UserInfo userphone= userService.findByMobile(phone);

		if (userphone == null){
			return new Result(true,StatusCode.OK,"该手机号可以注册");
		}
		return new Result(false,StatusCode.ERROR,"该手机号已经被注册");
	}

}
